package it.side.messaging.client;

import com.google.gwt.json.client.JSONParser;
import com.google.web.bindery.event.shared.EventBus;

public class MessageManager {

	private MessageFilter messageFilter;
	private EventBus eventBus;

	/**
	 * Costruisce un message manager che gestisce tutti i messaggi
	 * @param eventBus eventBus
	 */
	public MessageManager(EventBus eventBus) {
		this(eventBus, new MessageFilter() {
			@Override
			public boolean accept(Message message) {
				return true;
			}
		});
	}

	/**
	 * Costruisce un message manager che gestisci solo i messaggi accettati dal filtro
	 * @param eventBus eventBus
	 * @param messageFilter filtro per i messaggi
	 */
	public MessageManager(EventBus eventBus, MessageFilter messageFilter) {
		super();
		this.eventBus = eventBus;
		this.messageFilter = messageFilter;
	}
	
	/**
	 * Avvia il manager
	 */
	public void start() {
		register(this);
	}
	
	private final native void register(final MessageManager manager) /*-{
		 if ($wnd.addEventListener) {  // all browsers except IE before version 9
			$wnd.addEventListener("message", function(e) {
				manager.@it.side.messaging.client.MessageManager::onMessage(Ljava/lang/String;)(e.data);
			}, false);
		 } else {
            if ($wnd.attachEvent) {   // IE before version 9
                $wnd.attachEvent("onmessage", function(e) {
					manager.@it.side.messaging.client.MessageManager::onMessage(Ljava/lang/String;)(e.data);
				});
            }
         } 	
	}-*/;

	private final void onMessage(String message) {
		Message m = Message.fromJSON(JSONParser.parseStrict(message));
		if (eventBus!=null && messageFilter.accept(m)) {
			eventBus.fireEvent(new MessageEvent(m));
		}
	}
	
	public void sendMessage(Message message) {
		doPost(message.toJSON().toString());
	}
	
	public final native void doPost(String msg) /*-{
    	$wnd.parent.postMessage(msg, '*');
	}-*/;
	
}
